package cn.aws360.boot.wechat.biz.service.impl;

import cn.aws360.boot.base.api.exception.ServiceException;
import cn.aws360.boot.wechat.api.exception.WxmExceptionEnum;
import cn.aws360.boot.wechat.biz.service.WxMpPortalService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @author junnan
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WxMpPortalServiceImpl implements WxMpPortalService {


    @Override
    public boolean checkAuth(WxMpService mpService, String appId, String timestamp, String nonce, String signature) {
        if (!mpService.switchover(appId)) {
            throw new ServiceException(WxmExceptionEnum.WX_MP_AUTH_CONF_EXCEPTION, appId);
        }
        if (!mpService.checkSignature(timestamp, nonce, signature)) {
            throw new ServiceException(WxmExceptionEnum.WX_MP_AUTH_SIGN_EXCEPTION, appId);
        }
        return true;
    }

    @Override
    public String getAccessToken(WxMpService mpService) {
        try {
            return mpService.getAccessToken();
        } catch (WxErrorException e) {
            throw new ServiceException(WxmExceptionEnum.WX_MP_GET_TOKEN_EXCEPTION, e.getError().getErrorCode());
        }
    }

    @Override
    public String uploadTempMedia(WxMpService mpService, String mediaType, File tmpFile) {
        try {
            WxMpMaterialService materialService = mpService.getMaterialService();
            WxMediaUploadResult uploadResult = materialService.mediaUpload(mediaType, tmpFile);
            return uploadResult.getMediaId();
        } catch (WxErrorException e) {
            throw new ServiceException(WxmExceptionEnum.WX_MP_UPLOAD_MEDIA_EXCEPTION, e.getError().getErrorCode());
        }
    }

}
